﻿using System;
using UnityEngine.UIElements;
using winS.UnityEditor.UIElement;
using Button = winS.UnityEditor.UIElement.Button;
using TextField = winS.UnityEditor.UIElement.TextField;

namespace winS.UnityEditor.GUI
{
    public class CreateBar : VisualElement
    {
        public event Action onCancel;
        public event Action<string> onConfirm;

        public string label { get => textField.label.text; set => textField.label.text = value; }
        public string labelCancel { get => cancelButton.label.text; set => cancelButton.label.text = value; }
        public string labelConfirm { get => confirmButton.label.text; set => confirmButton.label.text = value; }

        private readonly Button cancelButton;
        private readonly Button confirmButton;
        private readonly TextField textField;

        internal CreateBar(GUIFactory guiFactory)
        {
            style.flexDirection = FlexDirection.Row;
            Add(textField = guiFactory.CreateTextField());
            textField.style.flexGrow = 1f;
            textField.textElement.RegisterCallback<KeyDownEvent>(KeyDownCallback);
            Add(confirmButton = EditorElementUtility.elementFactory.CreateButton("确认", OnConfirmCallback));
            Add(cancelButton = EditorElementUtility.elementFactory.CreateButton("取消", OnCancelCallback));
        }

        public new void Focus()
        {
            textField.textInput.Focus();
        }

        private void OnCancelCallback()
        {
            textField.value = null;
            onCancel?.Invoke();
        }
        private void OnConfirmCallback()
        {
            if (string.IsNullOrEmpty(textField.value)) return;
            onConfirm?.Invoke(textField.value);
            textField.value = null;
        }
        private void KeyDownCallback(KeyDownEvent keyDownEvent)
        {
            if (keyDownEvent.keyCode != UnityEngine.KeyCode.Return) return;
            OnConfirmCallback();
            keyDownEvent.StopImmediatePropagation();
        }
    }
}